from django.db import models
from django.contrib import admin
from tjango.ajax_select import *
from tjango.ajax_select.admin import *
from tjango.ajax_select.fields import *

from tjango.extra_admin.admin import *
from tjango.apps.formapago.models import *

class ChequeDeTerceroAdmin(admin.ModelAdmin):
	list_display = ['fecha','en_cartera','banco','numero','vencimiento','importe']
	def lookup_allowed(self, lookup, value):
		if lookup.startswith('movimientos'):
			return True
		return super(ChequeDeTerceroAdmin, self).lookup_allowed(lookup, value)		



class MovimientoChequeForm(forms.ModelForm):
	importe = forms.DecimalField(label='importe', required=False,widget=forms.TextInput( attrs={'readonly':'readonly'}))
	
	class Meta:
		model = MovimientoCheque

	def __init__(self, *args, **kwargs):
		super(MovimientoChequeForm, self).__init__(*args, **kwargs)		
		if kwargs.has_key('instance'):
			instance = kwargs['instance']
			self.initial['importe'] = instance.importe
			
class MovimientosCheques(admin.TabularInline):
	form = make_ajax_form(MovimientoCheque,dict(cheque='cheques'),superclass=MovimientoChequeForm)
	model = MovimientoCheque
	read_only_fields =['importe']
	verbose_name_plural="Cheques"
	
		
class MovimientoChequeAdmin(admin.ModelAdmin):
	form = MovimientoChequeForm	

class MovimientoCuentaInline(admin.TabularInline):
	model = MovimientoCuenta

class MovimientoCuentaAdmin(admin.ModelAdmin):
	list_display = ['fecha','tipo', 'cuenta','comprobante','vencimiento','importe_con_signo']
	list_filter= ['cuenta']
	def lookup_allowed(self, lookup, value):
		if lookup.startswith('formapago'):
			return True
		return super(MovimientoCuentaAdmin, self).lookup_allowed(lookup)		
		
class CuentaAdmin(admin.ModelAdmin):
	list_display = ['nombre','rubro']

class FormaPagoAdmin(admin.ModelAdmin):
	fields  = ['fecha','es_ingreso','efectivo']
	list_display = ['fecha','es_ingreso','efectivo_con_signo']
	date_hierarchy= 'fecha'
	inlines = [MovimientosCheques, MovimientoCuentaInline]

	def lookup_allowed(self, lookup, value):
		if lookup.startswith('efectivo'):
			return True
		return super(FormaPagoAdmin, self).lookup_allowed(lookup, value)		


class GastoAdmin(AjaxSelectAdmin):
	model = Gasto
	list_display = ['cuenta', 'concepto', 'fecha','total', 'comprobante']
	list_filter = ['fecha','cuenta']
	list_per_page = 100
	inlines = [MovimientosCheques, MovimientoCuentaInline]
	save_on_top = True
	fieldsets = ( 
			(None, {'fields': (( 'fecha', 'comprobante' ),('cuenta','concepto'),) }),
			('Forma de Pago', {'fields': ('efectivo',)}),
	)
	class Media:
		js = [
			"generic/jquery/jquery.js",
			"generic/forms/jquery-autocomplete/jquery.autocomplete.js",
			"generic/forms/ajax_select/js/ajax_select.js",
			]
		css = {
	           'all': ("generic/forms/jquery-autocomplete/jquery.autocomplete.css",'generic/forms/ajax_select/iconic.css')  
	          }

class ChequeLookup(object):

	def get_query(self,q,request):
		""" return a query set.  you also have access to request.user if needed """
		return ChequeDeTercero.objects.filter(numero__icontains=q)
                  
	def format_result(self, cheque):
		""" the search results display in the dropdown menu.  may contain html and multiple-lines. will remove any |  """
		return cheque.__unicode__()
                                      
	def format_item(self,cheque):
		""" the display of a currently selected object in the area below the search box. html is OK """
		return cheque.__unicode__()
                                                         
	def get_objects(self,ids):
		""" given a list of ids, return the objects ordered as you would like them on the admin page.
		this is for displaying the currently selected items (in the case of a ManyToMany field)
        """
		return ChequeDeTercero.objects.filter(pk__in=ids)


admin.site.register(TipoTarjeta)
admin.site.register(Tarjeta)
admin.site.register(Banco)
admin.site.register(CuentaBancaria)
admin.site.register(FormaDePago, FormaPagoAdmin)
admin.site.register(MovimientoCuenta, MovimientoCuentaAdmin)
admin.site.register(ChequeDeTercero, ChequeDeTerceroAdmin)
admin.site.register(MovimientoCheque, MovimientoChequeAdmin)
admin.site.register(Gasto, GastoAdmin)
admin.site.register(RubroCuenta)
admin.site.register(Cuenta, CuentaAdmin)
